package com.hanson.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hanson.Const;
import com.hanson.common.bean.ResultMessage;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.util.KuaidiUtil;
import com.hanson.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/kuaidi")
@Api(tags = "快递查询管理")
public class KuaiDiApiController {

    @Autowired
    private OrderService orderService;

    /**
     * 查询物流信息
     *
     * @return
     */
    @ApiOperation(value = "获取快递信息", notes = "获取快递信息")
    @RequestMapping(value = "/queryByNum/{no}", method = RequestMethod.GET)
    public ResultMessage queryByNum(@PathVariable String no) {
        log.info("获取快递信息：{}", no);
        ResultMessage resultMessage = new ResultMessage();
        String phone = orderService.selectPhoneByCourierNo(no);
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException(500, "系统无法查到当前快递号");
        }
        if (no.startsWith("SF")) {
            no = no + ":" + no.substring(no.length() - 4, no.length());
        }
        if (null == Const.kuaiDiCache.getIfPresent(no)) {
            JSONObject jsonObject = KuaidiUtil.getKuaiDiDetail(no);
            Integer status = jsonObject.getInteger("status");
            resultMessage.setCode(status);
            if (0 == status) {
                JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("list");
                log.info("查询结果：{}", jsonArray.toJSONString());
                resultMessage.setData(jsonArray);
            } else {
                resultMessage.setMsg(jsonObject.getString("msg"));
            }
        } else {
            resultMessage.setCode(0);
            resultMessage.setData(Const.kuaiDiCache.getIfPresent(no));
        }

        return resultMessage;
    }
}
